package net.orcspace.myplace.google;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.orcspace.myplace.data.AbstractDataProvider;
import net.orcspace.myplace.personal.todo.Todo;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;


public class GoogleDataProvider extends AbstractDataProvider{

//	GoogleDataProvider gdp = null;
	private DatastoreService datastore = null;
	private final String kindName="todo";

//	public static GoogleDataProvider getInstance(){
//		if(gdp==null)
//			gdp = new GoogleDataProvider();
//		
//		return gdp;
//	}
	
	public GoogleDataProvider(){
		datastore = DatastoreServiceFactory.getDatastoreService();
	}
	
	@Override
	public long addTodo(String todoItem) {
		Entity todo = new Entity(kindName);
		todo.getKey().getId();
		todo.setProperty("todoItem", todoItem);
		todo.setProperty("createTime", System.currentTimeMillis());		
		long key = datastore.put(todo).getId();
		//update the id
		todo.setProperty("id",key);
		datastore.put(todo);
		return key;
	}

	@Override
	public Todo getTodo(long id) {
		KeyFactory.Builder b = new KeyFactory.Builder(kindName,id);
		Todo todo = new Todo();
		try {
			Entity e = datastore.get(b.getKey());

			todo.setId((Long)e.getProperty("id"));
			todo.setTodoItem((String)e.getProperty("todoItem"));
			todo.setCreateTime((Long)e.getProperty("createTime"));
		} catch (EntityNotFoundException e) {
			e.printStackTrace();
		}
		
		return todo;
	}

	
	@Override
	public List<Todo> listAllTodo() {
		Query q = new Query(kindName);
		PreparedQuery pq = datastore.prepare(q);
		List<Todo> todos = new ArrayList<Todo>();
		for(Entity todo:pq.asIterable()){
			todos.add(getTodo(todo.getKey().getId()));
		}
		return todos;
	}
	@Override
	public void delAll(){
		Iterator<Todo> it = listAllTodo().iterator();
		long id = 0;
		while(it.hasNext()){
			id = it.next().getId();
			System.out.println("delete id="+id);
			delTodo(id);
		}
	}
	
	@Override
	public void delTodo(long id) {
		KeyFactory.Builder b = new KeyFactory.Builder(kindName,id);
		datastore.delete(b.getKey());
	}
	
}
